//
//  HZHomeListModel.swift
//  HansWeibo
//
//  Created by Hans on 16/8/13.
//  Copyright © 2016年 Hans. All rights reserved.
//

import UIKit

class HZHomeListModel: NSObject {
    // 保存微博数据数组
    var dataArray :[HZHomeViewModel] = [HZHomeViewModel]()
}


extension HZHomeListModel {
    // 请求首页数据  isPullUp 是否是上拉加载更多
    func loadData(isPullUp:Bool, finish:(isSusses: Bool)->()){
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        // 上拉 加载更多
        if isPullUp {
            maxId = dataArray.last?.homeModel?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else {
            // 下拉刷新
            sinceId = dataArray.first?.homeModel?.id ?? 0
        }
        
        
        HZNetworkTools.sharedTools.homeLoadData(sinceId, max_id: maxId, success: { (response) in
            //print("请求成功:\(response)")
            //判断response 是否为nil  而且是否能转成数组
            guard let res = response?["statuses"] as? [[String: AnyObject]] else {
                finish(isSusses: false)
                return
            }
            // 一个零时可变数组
            var tempArray: [HZHomeViewModel] = [HZHomeViewModel]()
            // 遍历数组
            for dict in res {
                let statuses = HZHomeModel(dict: dict)
                
                let homeViewModel = HZHomeViewModel(homeModel: statuses)
                
                tempArray.append(homeViewModel)
            }
            
            // 上拉加载更多
            if isPullUp {
                self.dataArray = self.dataArray + tempArray
            }else {
                // 下拉刷新
                self.dataArray = tempArray + self.dataArray
            }
            
            finish(isSusses: true)
        }) { (error) in
            //print("请求失败:\(error)")
            finish(isSusses: false)
        }
    }
}